#!/usr/bin/perl -w
#
#   $Id: getComingSoon.pl 3 2010-03-02 16:56:48Z alex@steamcalculator.com $
#
#   SteamCalculator Scripts - http://www.steamcalculator.com
#   Copyright (C) 2010 Alexander Kuhrt (alex@steamcalculator.com)
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use strict;
use DBI;
use LWP::Simple;
use POSIX qw(ceil strftime);
use Term::ANSIColor;
use Time::HiRes;
binmode(STDOUT, ":utf8");

require "./include/Simple.pm"; 
do "./include/functions.plib";

my $configFile = "./include/config.ini";
my @countries = ('at', 'de', 'uk', 'us');   # if you extend here, make sure to extend your database and 'fromDate' as well

my $start = [Time::HiRes::gettimeofday()];
my $db_host;
my $db_user;
my $db_pass;
my $db_name;

# read config file
if($configFile && -r $configFile)
{
    my $conf = ConfigReader::Simple->new($configFile);
    $conf->parse();

    $db_host = $conf->get("DBHostname");
    $db_user = $conf->get("DBUsername");
    $db_pass = $conf->get("DBPassword");
    $db_name = $conf->get("DBName");
}
else
{
    die("-- Warning: unable to open configuration file '$configFile'\n");
}

print "-- Connecting to MySQL database '$db_name' on '$db_host' as user '$db_user' ... ";

my $db = DBI->connect("DBI:mysql:$db_name:$db_host", $db_user, $db_pass) or die("\nCan't connect to MySQL database '$db_name' on '$db_host'\nServer error: $DBI::errstr\n");

print "connected [OK]\n";

for(my $c = 0; $c < @countries; $c++)
{
    my $country         = $countries[$c];

    print "-- Connecting to '$country' Steam Store ... ";

    my $steamStoreURL   = "http://store.steampowered.com/search/tab?tab=ComingSoon&start=0&cc=$country&v5=1";
    my $pageContent     = get($steamStoreURL);

    my %game;
   
    print "\n\n";
    print "============================================================================================================\n";
    print "||                                                                                                        ||\n";
    print "||  Loading '$country'                                             \n"; 
    print "||                                                                                                        ||\n";
    print "============================================================================================================\n";
    #print "|   Entries ".(($page - 1) * $gamesPerPage + 1)." - ".($page * $gamesPerPage)." of $totalEntries            \n";
    print "+-----+---------+---------+-------------+------------------------------------------------------------------+\n";
    print "|  #  |  AppID  |  Price  |   Release   |  Title                                                           |\n";
    print "+-----+---------+---------+-------------+------------------------------------------------------------------+\n";

    my $tempCursorPos  = 0;
    my $tempContent    = $pageContent ;

    for(my $i = 0; $i < 10; $i++)
    {
        # jump to next game
        $tempContent = substr($tempContent, $tempCursorPos);

        # grab game info
        $game{"appID"}[$i]     = cutter($tempContent, "/app/", "/");
        $game{"price"}[$i]     = formPrice(cutter($tempContent, "<div class=\"tab_price\">", "</div>"));
        $game{"release"}[$i]   = formDate(regExDate(cutter($tempContent, "</h4>", "</div>"), $country), $country);
        $game{"title"}[$i]     = cutter($tempContent, "<h4>", "</h4>");

        # set new cursor position
        $tempCursorPos = index($tempContent, "<br clear=\"all\">") + length("<br clear=\"all\">");

        # print result
        print sprintf("|% 4d |", $i);
        print sprintf("% 8d |", $game{"appID"}[$i]) ;
        print sprintf("% 8.2f |", $game{"price"}[$i]/ 100);
        print sprintf("% 12s |", date("%Y-%b-%d", $game{"release"}[$i]));
        print sprintf(" %s%".(65 - length($game{"title"}[$i]))."s|\n", $game{"title"}[$i], " ");

    }

    print "+-----+---------+---------+-------------+------------------------------------------------------------------+\n";

    # add games to database
    for(my $i = 0; $i < scalar(@{$game{"appID"}}); $i++)
    {
        my $query = qq{
            INSERT INTO sc_steamgames
            (
                `appid`,
                `title`,
                `releasedate`,
                `lastupdate`,
                `flags`
            )
            VALUES
            (
                ?,
                ?,
                ?,
                UNIX_TIMESTAMP(),
                2
            )
            ON DUPLICATE KEY UPDATE lastupdate = UNIX_TIMESTAMP(), flags = flags | 2
        };
        
        my $stmt = $db->prepare($query);
        my $res = $stmt->execute($game{"appID"}[$i], $game{"title"}[$i], $game{"release"}[$i]);
        $stmt->finish;

        $query = qq|
            INSERT INTO sc_steamgameprices
            (
                `appid`,
                $country 
            )
            VALUES
            (
                ?,
                ?
            )
            ON DUPLICATE KEY UPDATE $country = ?
        |;
        
        $stmt = $db->prepare($query);
        $res = $stmt->execute($game{"appID"}[$i], $game{"price"}[$i], $game{"price"}[$i]);
        $stmt->finish;
    }
}